
# -----------------------------------------------------------------------------
# a1.py
#
# A simple calculator with variables -- all in one file.
# -----------------------------------------------------------------------------

tokens = (
    'COMMA','NUMBER',
    'LPAREN','RPAREN',
    )

# Tokens

t_COMMA   = r','
t_LPAREN  = r'\('
t_RPAREN  = r'\)'

def t_NUMBER(t):
    r'\d+'
    try:
        t.value = int(t.value)
    except ValueError:
        print "Integer value too large", t.value
        t.value = 0
    return t

# Ignored characters
t_ignore = " \t"

def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")
    
def t_error(t):
    print "Illegal character '%s'" % t.value[0]
    t.lexer.skip(1)
    
# Build the lexer
import ply.lex as lex
lex.lex()

# Parsing rules

def p_statement(t):
	'statement : list'
	print t[1]

def p_list(t):
	'list : LPAREN sequence RPAREN'
	t[0] = "(" + t[2] + ")"
	

def p_empty_list(t):
	'list : LPAREN RPAREN'
	t[0] = "()"



def p_sequence(t):
    	'''sequence : listelement COMMA sequence
		| listelement'''
	if len(t) == 4 : t[0] = t[1] + "," +t[3]
	elif len(t) == 2 : t[0]=t[1]


def p_listelement_number(t):
    	'listelement : NUMBER'
	t[0]= str(t[1])


def p_listelement_list(t):
    	'listelement : list'
	t[0] = t[1] +""



def p_error(t):
    print "Syntax error at '%s'" % t.value

import ply.yacc as yacc
yacc.yacc()

while 1:
    try:
        s = raw_input('a1 > ')
    except EOFError:
        break
    yacc.parse(s)
